package com.woniuxy.health.customer.util;

import lombok.Data;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.*;

@Component
public class SpringWebSocket implements WebSocketHandler {

    private WebSocketSession webSocketSession;

    public WebSocketSession getWebSocketSession(){
        return webSocketSession;
    }
    //webSocket连接成功后调用
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        this.webSocketSession = session;
        System.out.println("SpringWebSocket:"+this.webSocketSession);
        System.out.println("SpringSocketHandle-----收到新的连接:" + session.getId());
    }

    //webSocket处理发送来的消息
    @Override
    public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
        System.out.println(message.getPayload());
        String msg = "SpringSocketHandle连接-----" + session.getId() +  ",已收到消息...";
        session.sendMessage(new TextMessage(msg));
    }

    //webSocket连接出错时调用
    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        System.out.println("webSocket 连接错误");
    }

    //webSocket连接关闭后调用
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
        System.out.println("webSocket 关闭连接");
        this.webSocketSession = null;
    }

    //是否支持分片消息
    @Override
    public boolean supportsPartialMessages() {
        return false;
    }
}
